-- Copyright (c) 2024 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.
local log = require 'mc.logging'
local context = require 'mc.context'
local client = require 'lsw.client'
local skynet = require 'skynet'

local SYSTEM_ID<const> = 1

local Event = {}

local function add_event(param)
    local ok, err = client:PEventsEventsAddEvent(context.new(), {SystemId = SYSTEM_ID}, param)
    if ok then
        return true
    else
        error('[lsw]generate event fail, err: %s', err)
    end
end

local RETRY_TIMES = 10
local function retry_add_event(param)
    for _ = 1, RETRY_TIMES do
        local ok, ret = pcall(add_event, param)
        if ok and ret then
            return true
        end
        skynet.sleep(50)
    end
    return false
end

--- 产生软件告警
function Event.generate_event(msg)
    if not msg then
        error('[lsw]generate event fail, msg is nil')
    end
    local param = {}
    for key, value in pairs(msg) do
        param[#param + 1] = { key, value }
    end

    local res = retry_add_event(param)
    if not res then
        error('[lsw]generate event fail')
    end
end

return Event